package property.personal.property_mange.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import property.personal.property_mange.pojo.ImageDataJson;
import property.personal.property_mange.pojo.Propertyinfo;
import property.personal.property_mange.service.impl.ProperImpl;
import property.personal.property_mange.service.impl.PropertyImpl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PropertyController {

    @Value("${upload.tmp.dir}")
    private String tmp;

    @Autowired
    PropertyImpl propertyImpl;

    @Autowired
    ProperImpl properimpl;

    @RequestMapping("/addProperty")
    public String addProperty(Propertyinfo propertyInfo){
        propertyInfo.setStatus("1");
        properimpl.addproperty(propertyInfo);
        return "addProperty";
    }

    @ResponseBody
    @RequestMapping("/addimage")
    public ImageDataJson addimage(MultipartFile  file)  {
        System.out.println("tmp=="+tmp);
        ImageDataJson dataJson=new ImageDataJson();

        File upload = new File(tmp);
        if(upload.exists()==false){
            upload.mkdirs();
        }

        String oldfilename=file.getOriginalFilename();
        int index=oldfilename.lastIndexOf(".");
        String extname=oldfilename.substring(index);
        String newfilename=System.currentTimeMillis()+extname;
        File descFile=new File(tmp,newfilename);
        try {
            file.transferTo(descFile);
            dataJson.setCode(1);
            dataJson.setMsg("上传成功");
            Map<String,String> map=new HashMap<>();
            map.put("src",newfilename);
            dataJson.setData(map);
        } catch (IOException e) {
            dataJson.setCode(0);
            dataJson.setMsg("上传失败");
            return dataJson;
        }
        return dataJson;
    }


}
